package com.yang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mzt.logapi.starter.annotation.LogRecord;
import com.yang.dao.entity.SkusDO;
import com.yang.dto.req.OrderDetailUpdateReqDTO;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.dao.entity.OrderDetailDO;
import com.yang.dao.mapper.OrderDetailMapper;
import com.yang.dto.req.OrderDetailPageQueryReqDTO;
import com.yang.dto.resp.OrderDetailPageQueryRespDTO;
import com.yang.service.OrderDetailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


/**
 * 订单详情业务实现层
 * 作者：孤城暖阳y
 * 开发时间：2025-03-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetailDO> implements OrderDetailService {

    private final OrderDetailMapper orderDetailMapper;
    private final MongoTemplate mongoTemplate;

    @Override
    public IPage<OrderDetailPageQueryRespDTO> pageQueryOrderDetail(OrderDetailPageQueryReqDTO requestParam) {
        // 构建订单详情查询条件
        LambdaQueryWrapper<OrderDetailDO> queryWrapper = Wrappers.lambdaQuery(OrderDetailDO.class)
                .eq(Objects.nonNull(requestParam.getOrderDetailId()),
                        OrderDetailDO::getOrderDetailId, requestParam.getOrderDetailId())
                .eq(Objects.nonNull(requestParam.getUserId()),
                        OrderDetailDO::getUserId, requestParam.getUserId())
                .eq(Objects.nonNull(requestParam.getStatus()),
                        OrderDetailDO::getStatus, requestParam.getStatus())
                .between(Objects.nonNull(requestParam.getStartTime()) && Objects.nonNull(requestParam.getEndTime()),
                        OrderDetailDO::getCreateTime, requestParam.getStartTime(), requestParam.getEndTime());

        // 查询
        IPage<OrderDetailPageQueryRespDTO> respDTOIPage = orderDetailMapper.pageQueryOrderDetail(
                new Page<>(requestParam.getCurrent(), requestParam.getSize()),
                queryWrapper
        );
        // 查询skuId对应的name和valueName
        List<SkusDO> skusDOS;
        for (OrderDetailPageQueryRespDTO respDTO : respDTOIPage.getRecords()) {
            // mongoDB获取sku数据
            Query query = new Query(Criteria.where("skuId").is(respDTO.getSkuId()));
            skusDOS = mongoTemplate.find(query, SkusDO.class);
            // TODO 待优化。其次MongoDB中skuId的数据类型是字符串类型后续需要改为长整型
            respDTO.setSkuName(skusDOS.getFirst().getSpecs().getFirst().getName());
            respDTO.setSkuValueName(skusDOS.getFirst().getSpecs().getFirst().getValueName());
        }
        return respDTOIPage;
    }

    @Override
    @Transactional
    @LogRecord(
            success = """
                    订单详情id：{{#requestParam.orderDetailId}}， \
                    姓名：{{#requestParam.ReceiverName}}， \
                    手机号：{{#requestParam.ReceiverPhone}}， \
                    地址：{{#requestParam.receiverReceiverDescription}}， \
                    """,
            type = "orderDetailUpdate",
            bizNo = "{{#requestParam.orderDetailId}}",
            extra = "{{#requestParam.toString()}}"
    )
    public void updateOrderDetail(OrderDetailUpdateReqDTO requestParam) {
        UpdateWrapper<OrderDetailDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("order_detail_id", requestParam.getOrderDetailId())
                .set(requestParam.getReceiverName() != null, "receiver_name", requestParam.getReceiverName())
                .set(requestParam.getReceiverPhone() != null, "receiver_phone", requestParam.getReceiverPhone())
                .set(requestParam.getReceiverAddressDescription() != null, "receiver_address_description", requestParam.getReceiverAddressDescription())
                .set(requestParam.getStatus() != null, "status", requestParam.getStatus());

        if (!update(updateWrapper)) {
            throw new RuntimeException("更新失败");
        }
    }

    @Override
    public Long getOrderCountUndeliveredCount() {
        LambdaQueryWrapper<OrderDetailDO> queryWrapper = Wrappers.lambdaQuery(OrderDetailDO.class)
                .eq(OrderDetailDO::getStatus, 2);
        return orderDetailMapper.selectCount(queryWrapper);
    }

    @Override
    public Long getTodaySales() {
        // 获取当天开始和结束时间
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.plusDays(1).atStartOfDay();

        // 构建查询条件
        LambdaQueryWrapper<OrderDetailDO> queryWrapper = Wrappers.lambdaQuery(OrderDetailDO.class)
                .eq(OrderDetailDO::getStatus, 5)
                .between(OrderDetailDO::getCreateTime, startOfDay, endOfDay);

        return orderDetailMapper.selectCount(queryWrapper);
    }
}
